import React, {Component} from 'react';
import {withStore} from '../store/storeUtils';
import AppTabBar from "./AppTabBar";
import AppHeader from "./AppHeader";
import {renderRoutes} from 'react-router-config';
import {routers as rootRouter} from "../router/rootRouter";
import './RealApp.less';
import {fetchMe} from '../api/userApi';
import {resolveSearch} from '../util/UrlUtils';
import WxApi from '../wx/WxApi';


class RealApp extends Component {
    componentDidMount() {
        this.token = null;
        this.resolveTokenInSearch();
        const token = this.token || this.props.storeState.token.tokenStr;
        this.props.actions.setToken(token, {});
        if (token) {
            console.log('Login with token:', token);
            this.fetchMe(token);
        }
    }

    resolveTokenInSearch() {
        const searchParams = resolveSearch();
        const {token} = searchParams;
        this.token = token;
    }

    fetchMe(token) {
        fetchMe().then(res => {
            this.props.actions.setToken(token, res);
            WxApi.init(res);
        });
    }

    render() {
        return (
            <div className="app-root">
                <div className="header-wrapper">
                    <AppHeader/>
                </div>
                <div className="app-content">
                    {
                        renderRoutes(rootRouter)
                    }
                    <div className="tab-bar-mask"/>
                </div>
                <AppTabBar/>
            </div>
        );
    }
}

export default withStore(RealApp);